#!/usr/bin/python
# Mode: -*- python -*-
#
# Copyright (c) 2000-2002 by hartmut Goebel <hartmut@goebel.noris.de>
#
"""
Usage: unpyc [OPTIONS]... [ FILE | DIR]...

Examples:
  unpyc      foo.pyc bar.pyc       # unpyc foo.pyc, bar.pyc to stdout
  unpyc -o . foo.pyc bar.pyc       # unpyc to ./foo.dis and ./bar.dis
  unpyc -o /tmp /usr/lib/python1.5 # unpyc whole library

Options:
  -o <path>     output decompiled files to this path:
                if multiple input files are decompiled, the common prefix
                is stripped from these names and the remainder appended to
                <path>
                  unpyc -o /tmp bla/fasel.pyc bla/foo.pyc
                    -> /tmp/fasel.dis, /tmp/foo.dis
                  unpyc -o /tmp bla/fasel.pyc bar/foo.pyc
                    -> /tmp/bla/fasel.dis, /tmp/bar/foo.dis
                  unpyc -o /tmp /usr/lib/python1.5
                    -> /tmp/smtplib.dis ... /tmp/lib-tk/FixTk.dis
  -c <code>     attempts a disassembly after compiling <code
  -d            do not print timestamps
  --verify      compare generated source with input byte-code
                (requires -o)
  --help        show this message

Debugging Options:
  --showasm   -a  include byte-code                  (disables --verify)
  --showast   -t  include AST (abstract syntax tree) (disables --verify)

Extensions of generated files:
  '.dis'             successfully decompiled (and verified if --verify)
  '.dis_unverified'  successfully decompile but --verify failed
  '.nodis'           unpyc failed (contact author for enhancement)
"""

Usage_short = \
"decomyple [--help] [--verify] [--showasm] [--showast] [-o <path>] FILE|DIR..."

import sys, os, getopt
import os.path
from unpyc import main, verify
import time

showasm = showast = do_verify = 0
outfile = '-'
out_base = None
codes = []
timestamp = True
timestampfmt = "# %Y.%m.%d %H:%M:%S %Z"

try:
    opts, files = getopt.getopt(sys.argv[1:], 'hatdo:c:',
                           ['help', 'verify', 'showast', 'showasm'])
except getopt.GetoptError, e:
    print >>sys.stderr, '%s: %s' % (os.path.basename(sys.argv[0]), e)
    sys.exit(-1)    

for opt, val in opts:
    if opt in ('-h', '--help'):
        print __doc__
        sys.exit(0)
    elif opt == '--verify':
        do_verify = 1
    elif opt in ('--showasm', '-a'):
        showasm = 1
        do_verify = 0
    elif opt in ('--showast', '-t'):
        showast = 1
        do_verify = 0
    elif opt == '-o':
        outfile = val
    elif opt == '-d':
        timestamp = False
    elif opt == '-c':
        codes.append(val)
    else:
        print Usage_short
        sys.exit(1)

# argl, commonprefix works on strings, not on path parts,
# thus we must handle the case with files in 'some/classes'
# and 'some/cmds'
src_base = os.path.commonprefix(files)
if src_base[-1:] != os.sep:
    src_base = os.path.dirname(src_base)
if src_base:
    sb_len = len( os.path.join(src_base, '') )
    files = map(lambda f: f[sb_len:], files)
    del sb_len
    
if outfile == '-':
    outfile = None # use stdout
elif outfile and os.path.isdir(outfile):
    out_base = outfile; outfile = None
elif outfile and len(files) > 1:
    out_base = outfile; outfile = None

if timestamp:
    print time.strftime(timestampfmt)

try:
    main(src_base, out_base, files, codes, outfile, showasm, showast, do_verify)
except KeyboardInterrupt, OSError:
    pass
except verify.VerifyCmpError:
    raise

if timestamp:
    print time.strftime(timestampfmt)
